package com.effectiv.crm.etl.impl;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Named;

import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

import com.effectiv.crm.domain.FileUploadDetails;
import com.effectiv.crm.etl.api.ExtractStrategy;

@Slf4j
@Named
public class CsvExtractStrategy implements ExtractStrategy {

	private final String acceptedTypes[] = { "text/comma-separated-values",
			"text/csv", "application/csv" };

	@Override
	public boolean canExtract(FileUploadDetails fileDetails) {
		return StringUtil.equalsOneIgnoreCase(fileDetails.getContentType(),
				acceptedTypes) != -1;
	}

	@Override
	public List extract(FileUploadDetails fileDetails, Class c) {
		log.info("Reading from csv file");
		
		List sRows = null;

		try (BufferedReader br = new BufferedReader(new InputStreamReader(
				fileDetails.getInputStream(), "UTF-8"))) {

			String line = null;
			sRows = new ArrayList();

			if (fileDetails.isHeader()) {
				// Move cursor beyond header
				log.info("Header present moving cursor.");
				br.readLine();
			}

			while ((line = br.readLine()) != null) {
				sRows.add(line);
			}

		} catch (Exception e) {
			log.error("Error", e);
		}
		
		
		log.info("Rows = {}",sRows);
		
		
		return sRows;
	}

}
